#include "../Codec/ICodec.h"
#include "PictureAdder.h"
#include "../Timestamp.h"
#include "../Codec/Codec.h"
#include "../currentThread.h"

#include <fstream>
#include <unistd.h>
#include <sys/syscall.h>
#include <muduo/base/Logging.h>


PictureAdder::PictureAdder()
     : ICodec_(new Codec) 
       {}

void PictureAdder::setInitialContent(const std::string &initialContent) {
    ICodec_->setInitialContent(initialContent);
}

std::string PictureAdder::addMark() {
    std::string sourceImageFileName = "image/image/src" + Timestamp::now().toString() +
            currentThread::getTidAsString() + ".png";
    std::string logoImageFileName = "image/image/logo" + Timestamp::now().toString() +
                                      currentThread::getTidAsString() + ".png";
    std::string retImageName = "image/image/ret" + Timestamp::now().toString() +
                                      currentThread::getTidAsString() + ".png";
    ICodec_->decode();
    saveFile(sourceImageFileName, ICodec_->getResultContentDecodeContent1());
    saveFile(logoImageFileName, ICodec_->getResultContentDecodeContent2());

    cv::Mat sourceImage = cv::imread(sourceImageFileName);
    cv::Mat logoImage = cv::imread(logoImageFileName);

    if (sourceImage.empty()) {
        fprintf(stderr, "Adder::addMarkByImage(): source image is empty!\n");
        return "";
    }

    if (logoImage.empty()) {
        fprintf(stderr, "Adder::addMarkByImage(): logo image is empty!\n");
        return "";
    }

    cv::Mat logoResizeImage;
    cv::Mat retImage;

    cv::resize(logoImage, logoResizeImage, sourceImage.size());
    cv::addWeighted(sourceImage, 1.0, logoResizeImage, 0.3, 0, retImage);
    saveFile(retImageName, retImage);

    deleteFile(sourceImageFileName);
    deleteFile(logoImageFileName);
    
    return retImageName;
}

void PictureAdder::saveFile(const std::string &fileName, const std::string &fileContent) {
    std::ofstream file(fileName);
    file <<fileContent;
    file.close();
}

void PictureAdder::saveFile(const std::string &fileName, cv::Mat fileContent) {
    cv::imwrite(fileName, fileContent);
}

void PictureAdder::deleteFile(const std::string &fileName)
{
    int isOK = ::unlink(fileName.c_str());
    if (isOK < 0)
        LOG_INFO << "PictureAdder::deleteFile(): remove file failed";
}
